package playback;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class UClip {

	private byte[] aData;
	private Clip clip;
	private boolean readyToPlay = false;
	private AudioFormat format;
	
	public UClip(AudioFormat af, UClip... c) {
		int count = 0;
		for (UClip cc: c) {
			count += cc.getByteLength();
		}
		aData = new byte[count];
		int loc = 0;
		for (UClip cc: c) {
			for (byte b: cc.getBytes()) {
				aData[loc] = b;
				loc++;
			}
		}
		format = af;
	}
	
	public UClip(AudioFormat af, byte[] b) {
		aData = b;
		format = af;
	}
	
	
	public int getByteLength() {
		return aData.length;
	}
	
	public byte[] getBytes() {
		return aData;
	}
	
	public boolean isReadyForPlayback() {
		return readyToPlay;
	}
	
	public boolean initPlayback() {
		if (readyToPlay) return true;
		try {
			clip = AudioSystem.getClip();
			clip.open(format, aData, 0, aData.length);
			readyToPlay = true;
		} catch (Exception e) {
			readyToPlay = false;
		}
		return readyToPlay;
	}
	
	public boolean play() {
		if (!readyToPlay) return false;
		clip.start();
		return true;
	}
	
	public int getFramePosition() {
		if (!readyToPlay) return -1;
		return clip.getFramePosition();
	}
	
	public boolean stop() {
		if (!readyToPlay) return true;
		clip.stop();
		return true;
	}
	
	

}
